<template>
  <div class="app-container">
    <el-card shadow="never">
      <!-- 警告区域 -->
      <el-alert
        show-icon
        :title="$t('user.tip')"
        type="warning"
        :closable="false"
      ></el-alert>
      <!-- 选择分类区域 -->
      <el-row
        class="cat_opt"
        style="margin-top:10px"
      >
        <el-col>
          <span>{{$t('user.select')}}：</span>
          <!-- 选择框 -->
          <el-select
            v-model="selected"
            filterable
            clearable
            :placeholder="$t('common.select')"
            @change="fetchCertificateByUser(selected)"
          >
            <el-option
              v-for="item in optionfen"
              :key="item.user_id"
              :label="item.username"
              :value="{ value: item.username, key: item.user_id}"
            >
            </el-option>
            <div style="bottom: -10px">
              <el-pagination
                small
                @current-change="handleCurrentChange"
                :current-page="currentpage"
                :page-size="pageSize"
                layout="prev, pager,next,total"
                :total="userList.length"
              >
              </el-pagination>
            </div>
          </el-select>
        </el-col>
      </el-row>
      <!-- 添加、删除按钮 -->
      <div align="right">
        <el-button
          type="success"
          size="medium"
          @click="showAddDialog"
        >{{$t('usercertificate.add')}}</el-button>
        <el-button
          type="danger"
          size="medium"
          @click="delAllCertificate"
        >{{$t('usercertificate.deleteAll')}}</el-button>
      </div>

      <!-- 所有证书列表 -->
      <el-table
        :data="certificateList"
        border
        stripe
      >

        <el-table-column
          align="center"
          width="70"
          :label="$t('certificatelist.table.certificate_id')"
        >
          <template slot-scope="scope">
            {{ scope.row.certificate_id }}
          </template>
        </el-table-column>

        <el-table-column
        :label="$t('certificatelist.table.name')"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>

        <el-table-column
        :label="$t('certificatelist.table.part')"
          width="90"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.part }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          :label="$t('certificatelist.table.content')"
        >
          <template slot-scope="scope">
            {{ scope.row.content }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          width="50"
          :label="$t('certificatelist.table.number_target')"
        >
          <template slot-scope="scope">
            {{ scope.row.number_target }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          width="50"
          :label="$t('certificatelist.table.time_target')"
        >
          <template slot-scope="scope">
            {{ scope.row.time_target }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          width="50"
          :label="$t('certificatelist.table.score_target')"
        >
          <template slot-scope="scope">
            {{ scope.row.score_target }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          width="50"
          :label="$t('certificatelist.table.pay_target')"
        >
          <template slot-scope="scope">
            {{ scope.row.pay_target }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          width="50"
          :label="$t('certificatelist.table.like_target')"
        >
          <template slot-scope="scope">
            {{ scope.row.like_target }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          width="50"
          :label="$t('certificatelist.table.collect_target')"
        >
          <template slot-scope="scope">
            {{ scope.row.collect_target }}
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('common.operate')"
          align="center"
          width="200"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-share"
              @click="getPDF(scope.row.certificate_id,selected)"
            >{{$t('common.upload')}}</el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="delUserCer(scope.row.certificate_id,selected)"
            >
              {{$t('common.delete')}}
            </el-button>
          </template>
        </el-table-column>

      </el-table>
      <!-- 分页 -->
      <div
        class="block"
        style="float: right; margin-top: 20px"
      >
        <!-- <span class="demonstration">显示总数</span> -->
        <el-pagination
          background
          @current-change="fetchCertificateByUser(selected)"
          :current-page.sync="page_num"
          :page-size="page_size"
          layout="total, prev, pager, next"
          :total="total"
        >
        </el-pagination>
        <!-- 对话框 -->
        <el-dialog
          :title="$t('usercertificate.add')"
          :visible.sync="dialogFormVisible"
        >
          <el-form
            style="width: 80%"
            :model="certificate_form"
          >
            <el-form-item
              label="证书ID："
              label-width="120px"
            >
              <el-input
                autocomplete="off"
                v-model="certificate_form.certificate_id"
              ></el-input>
            </el-form-item>

          </el-form>
          <div
            slot="footer"
            class="dialog-footer"
          >
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button
              type="primary"
              @click="addCertificate"
            >确 定</el-button>
          </div>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>

<script>
import certificate from "@/api/certificatemanage";
export default {
  name: "usercertificate",
  data() {
    return {
      selected: "", //输入框的值
      userList: [], //用户列表总数据
      optionfen: [], //当前页码的数据
      currentpage: 1, //当前页码
      pageSize: 8, //每页展示的条数

      certificateList: [], //证书列表
      page_num: 1,
      page_size: 8, //每8个数据一页
      total: 0,
      certificate_form: {},
      selectedUserID: 0, //选中用户id
      dialogFormVisible: false, //对话框
    };
  },
  created() {
    this.fetchUserList();
  },
  methods: {
    //选择框分页
    //分页的实现,currentpage 为页码，每页展示的数据为8（可自行更改pageSize）条，分别是在总数据userList中
    handleCurrentChange(val) {
      this.optionfen = [];
      this.currentpage = val;
      let start = (val - 1) * this.pageSize;
      let end = Number(start) + Number(this.pageSize);
      //此处需要判断如果计算的结束下标大于总数据的长度，则需要修改结束下标
      if (end > this.userList.length) {
        end = this.userList.length;
      }
      for (let i = start; i < end; i++) {
        //将取到的数据展示在页面
        this.optionfen.push(this.userList[i]);
      }
      // console.log(this.optionfen);
    },
    //获取选项框用户列表
    fetchUserList() {
      var vm = this;
      certificate
        .getUserList(this.page_num, 1000)
        .then((res) => {
          // console.log(res);
          this.userList = res.data.userList.list;
          // console.log(this.userList);
          for (let i = 0; i < 8; i++) {
            //将取到的数据展示在页面
            this.optionfen.push(this.userList[i]);
          }
        })
        .catch((error) => {
          console.log("error");
        });
    },
    //根据所选用户渲染该证书列表
    fetchCertificateByUser(selectedUser) {
      this.selectedUserID = selectedUser.key;
      // console.log('id',this.selectedUserID)
      certificate
        .getCertificateByUser(
          this.page_num,
          this.page_size,
          this.selectedUserID
        )
        .then((res) => {
          // console.log(res);
          this.certificateList = [];
          if (res.data.certificateList.size != 0) {
            this.certificateList = res.data.certificateList.list;
            this.total = res.data.certificateList.total;
          } else {
            //提示
            this.$message({
              type: "error",
              message: "该用户暂无证书数据！",
            });
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    //添加对话框显示
    showAddDialog() {
      this.dialogFormVisible = true;
      this.certificate_form = {};
    },
    //添加证书
    addCertificate() {
      //把所选的用户信息转化为对象
      let selectedObj = {
        data: this.selected,
      };
      // console.log(selectedObj);
      certificate
        .addCertificateToUser(
          this.certificate_form.certificate_id,
          selectedObj.data.key
        )
        .then((res) => {
          // console.log(res)
          if (res.errorCode == 0) {
            this.$message({
              type: "success",
              message: "添加成功!",
            });
            this.dialogFormVisible = false;
            this.fetchCertificateByUser(selected);
          } else {
            this.$message({
              type: "error",
              message: "添加失败!",
            });
          }
        })
        .catch((error) => {});
    },
    //删除用户所有的证书
    delAllCertificate() {
      //把所选的用户信息转化为对象
      let selectedObj = {
        data: this.selected,
      };
      this.$confirm("此操作将永久删除该所有证书, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //调用接口
          certificate
            .delUserAllCertificate(selectedObj.data.key)
            .then((res) => {
              //提示
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              //刷新页面数据
              this.fetchCertificateByUser(selected);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //获得证书pdf
    getPDF(certificate_id, selected) {
      // console.log(certificate_id + "----" + selected.key);
      certificate
        .getCerPdf(certificate_id, selected.key)
        .then((res) => {
          // console.log(res);
          let url = window.URL.createObjectURL(new Blob([res]));
          let link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute("download", "证书.pdf");
          document.body.appendChild(link);
          link.click();
        })
        .catch((error) => {
          this.$message.error("下载失败");
        });
    },

    //删除用户某个证书
    delUserCer(certificate_id, selected) {
      this.$confirm("此操作将永久删除该所有证书, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //调用接口
          certificate
            .delUserCertificate(certificate_id, selected.key)
            .then((res) => {
              //提示
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              //刷新页面数据
              this.fetchCertificateByUser(selected);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
